<?php

class DBQuery
{

    private static $dbLink = "";
    private static $instance = null;

    public function __construct($connectionParameters = "", $customConnection = false)
    {
        if($customConnection)
        {
            DBQuery::$dbLink = $this->customConnect($connectionParameters);
            DBQuery::$instance = $this;
        }
        else
        {
            DBQuery::$dbLink = $this->connect();
        }
    }

    public static function getInstance()
    {
        if(empty(DBQuery::$instance) || empty(DBQuery::$dbLink))
        {
            DBQuery::$instance = new DBQuery();
        }

        return DBQuery::$instance;
    }

    public function __destroy()
    {
        $this->close(DBQuery::$dbLink);
    }

    public function executeQuery($query)
    {
        $result = array();

        $resource = mysql_query($query, DBQuery::$dbLink) or die(mysql_error());
        $numFields = mysql_num_fields($resource);

        while($row = mysql_fetch_array($resource, MYSQL_ASSOC))
        {
            $aRow = array();

            for($i = 0; $i < $numFields; $i++)
            {
                $fieldName = mysql_field_name($resource, $i);
                $aRow[$fieldName] = $row[$fieldName];
            }

            array_push($result, $aRow);
        }

        mysql_free_result($resource);

        return $result;
    }

    public function executeNonQuery($query)
    {
        $querySuccessful = mysql_query($query, DBQuery::$dbLink);

        if(!$querySuccessful)
        {
//	    Log::logQueryError("Query error : $query");
        }
        else
        {
            $newId = mysql_insert_id();

            return $newId;
        }
    }

    private function connect()
    {
//        $db = $_SESSION['db'];
        $link = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
        mysql_select_db($db['default']['database'], $link);

        return $link;
    }

    private function customConnect($connectionParameters)
    {
        $link = mysql_connect($connectionParameters['host'], $connectionParameters['username'],
                $connectionParameters['password']);
        mysql_select_db($connectionParameters['database'], $link);

        return $link;
    }

    private function close($dbLink)
    {
        return mysql_close($dbLink);
    }

    public function beginTransaction()
    {
        mysql_query("BEGIN");
    }

    public function commitTransaction()
    {
        mysql_query("COMMIT");
    }

    public function rollbackTransaction()
    {
        mysql_query("ROLLBACK");
    }

}

?>